import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
  Dimensions,
  Linking,
  Share,
} from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import ProgressiveImage from './components/ProgressiveImage';
import ImageViewer from './components/ImageViewer';
import Car3DViewer from './components/Car3DViewer';
import { carAPI } from '../services/api';

const { width } = Dimensions.get('window');

interface Car {
  _id: string;
  brand: string;
  model: string;
  year: number;
  price: number;
  mileage: number;
  fuelType: string;
  transmission: string;
  color: string;
  condition: string;
  description: string;
  images: string[];
  location: string;
  contact: string;
  createdAt: string;
  updatedAt: string;
}

interface RouteParams {
  carId: string;
}

const CarDetailScreen: React.FC = () => {
  const route = useRoute();
  const navigation = useNavigation();
  const { carId } = route.params as RouteParams;
  
  const [car, setCar] = useState<Car | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [imageViewerVisible, setImageViewerVisible] = useState(false);
  const [car3DViewerVisible, setCar3DViewerVisible] = useState(false);

  useEffect(() => {
    loadCarDetail();
  }, [carId]);

  const loadCarDetail = async () => {
    try {
      setLoading(true);
      const response = await carAPI.getCarById(carId);
      setCar(response.data);
    } catch (error) {
      console.error('加载车辆详情失败:', error);
      Alert.alert('错误', '加载车辆详情失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleCall = () => {
    if (car?.contact) {
      Linking.openURL(`tel:${car.contact}`);
    }
  };

  const handleShare = async () => {
    if (car) {
      try {
        await Share.share({
          message: `看看这辆${car.brand} ${car.model}！\n年份：${car.year}年\n价格：¥${car.price.toLocaleString()}\n里程：${car.mileage}km\n位置：${car.location}\n联系方式：${car.contact}`,
          title: `${car.brand} ${car.model}`,
        });
      } catch (error) {
        console.error('分享失败:', error);
      }
    }
  };

  const handleImagePress = (index: number) => {
    setCurrentImageIndex(index);
    setImageViewerVisible(true);
  };

  const handle3DView = () => {
    setCar3DViewerVisible(true);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
        <Text style={styles.loadingText}>加载中...</Text>
      </View>
    );
  }

  if (!car) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>车辆信息不存在</Text>
        <TouchableOpacity style={styles.retryButton} onPress={loadCarDetail}>
          <Text style={styles.retryButtonText}>重试</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
             {/* 头部图片区域 */}
       <View style={styles.imageSection}>
         {car.images && car.images.length > 0 ? (
           <>
             <View style={styles.mainImageContainer}>
               <ProgressiveImage
                 uri={car.images[currentImageIndex]}
                 thumbnailUri={car.images[currentImageIndex]}
                 style={styles.mainImage}
               />
               <TouchableOpacity
                 style={styles.view3DButton}
                 onPress={handle3DView}
                 activeOpacity={0.8}
               >
                 <Text style={styles.view3DButtonText}>🔍 3D看车</Text>
               </TouchableOpacity>
             </View>
             {car.images.length > 1 && (
               <View style={styles.thumbnailContainer}>
                 <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                   {car.images.map((image, index) => (
                     <TouchableOpacity
                       key={index}
                       onPress={() => handleImagePress(index)}
                       style={[
                         styles.thumbnail,
                         index === currentImageIndex && styles.activeThumbnail,
                       ]}
                     > 
                       <ProgressiveImage
                         uri={image}
                         thumbnailUri={image}
                         style={styles.thumbnailImage}
                       />
                     </TouchableOpacity>
                   ))}
                 </ScrollView>
               </View>
             )}
           </>
         ) : (
           <View style={styles.noImageContainer}>
             <Text style={styles.noImageText}>暂无图片</Text>
           </View>
         )}
       </View>

      {/* 基本信息 */}
      <View style={styles.infoSection}>
        <View style={styles.titleRow}>
          <Text style={styles.title}>{car.brand} {car.model}</Text>
          <Text style={styles.year}>({car.year}年)</Text>
        </View>
        
        <View style={styles.priceRow}>
          <Text style={styles.price}>¥{car.price.toLocaleString()}</Text>
          <View style={styles.conditionBadge}>
            <Text style={styles.conditionText}>{car.condition}</Text>
          </View>
        </View>

        <View style={styles.basicInfo}>
          <View style={styles.infoItem}>
            <Text style={styles.infoLabel}>里程</Text>
            <Text style={styles.infoValue}>{car.mileage.toLocaleString()}km</Text>
          </View>
          <View style={styles.infoItem}>
            <Text style={styles.infoLabel}>燃料</Text>
            <Text style={styles.infoValue}>{car.fuelType}</Text>
          </View>
          <View style={styles.infoItem}>
            <Text style={styles.infoLabel}>变速箱</Text>
            <Text style={styles.infoValue}>{car.transmission}</Text>
          </View>
          <View style={styles.infoItem}>
            <Text style={styles.infoLabel}>颜色</Text>
            <Text style={styles.infoValue}>{car.color}</Text>
          </View>
        </View>
      </View>

      {/* 详细描述 */}
      {car.description && (
        <View style={styles.descriptionSection}>
          <Text style={styles.sectionTitle}>车辆描述</Text>
          <Text style={styles.descriptionText}>{car.description}</Text>
        </View>
      )}

      {/* 位置和联系信息 */}
      <View style={styles.contactSection}>
        <Text style={styles.sectionTitle}>联系信息</Text>
        
        <View style={styles.contactItem}>
          <Text style={styles.contactLabel}>📍 位置</Text>
          <Text style={styles.contactValue}>{car.location}</Text>
        </View>
        
        <View style={styles.contactItem}>
          <Text style={styles.contactLabel}>📞 联系电话</Text>
          <Text style={styles.contactValue}>{car.contact}</Text>
        </View>

        <View style={styles.contactItem}>
          <Text style={styles.contactLabel}>📅 发布时间</Text>
          <Text style={styles.contactValue}>{formatDate(car.createdAt)}</Text>
        </View>
      </View>

      {/* 操作按钮 */}
      <View style={styles.actionSection}>
        <TouchableOpacity style={styles.callButton} onPress={handleCall}>
          <Text style={styles.callButtonText}>📞 立即联系</Text>
        </TouchableOpacity>
        
        <TouchableOpacity style={styles.shareButton} onPress={handleShare}>
          <Text style={styles.shareButtonText}>📤 分享车辆</Text>
        </TouchableOpacity>
      </View>

      {/* 底部间距 */}
      <View style={styles.bottomSpacing} />
      
             {/* 图片查看器 */}
       {car && car.images && car.images.length > 0 && (
         <ImageViewer
           visible={imageViewerVisible}
           images={car.images}
           initialIndex={currentImageIndex}
           onClose={() => setImageViewerVisible(false)}
         />
       )}

       {/* 3D车辆查看器 */}
       {car && (
         <Car3DViewer
           visible={car3DViewerVisible}
           carBrand={car.brand}
           carModel={car.model}
           onClose={() => setCar3DViewerVisible(false)}
         />
       )}
     </ScrollView>
   );
 };

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
  },
  errorText: {
    fontSize: 16,
    color: '#666',
    marginBottom: 20,
  },
  retryButton: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    backgroundColor: '#007AFF',
    borderRadius: 8,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '600',
  },
  imageSection: {
    backgroundColor: 'white',
    paddingBottom: 16,
  },
  mainImageContainer: {
    position: 'relative',
    width: width,
    height: width * 0.75,
  },
  mainImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  },
  view3DButton: {
    position: 'absolute',
    top: 16,
    right: 16,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.3)',
  },
  view3DButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
  thumbnailContainer: {
    paddingHorizontal: 16,
    marginTop: 16,
  },
  thumbnail: {
    marginRight: 12,
    borderRadius: 8,
    borderWidth: 2,
    borderColor: 'transparent',
  },
  activeThumbnail: {
    borderColor: '#007AFF',
  },
  thumbnailImage: {
    width: 60,
    height: 60,
    borderRadius: 6,
    resizeMode: 'cover',
  },
  noImageContainer: {
    width: width,
    height: width * 0.75,
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  noImageText: {
    fontSize: 16,
    color: '#999',
  },
  infoSection: {
    backgroundColor: 'white',
    padding: 20,
    marginTop: 12,
  },
  titleRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    flex: 1,
  },
  year: {
    fontSize: 16,
    color: '#666',
  },
  priceRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 20,
  },
  price: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#FF6B35',
  },
  conditionBadge: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
  },
  conditionText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '600',
  },
  basicInfo: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  infoItem: {
    width: '48%',
    marginBottom: 16,
  },
  infoLabel: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  infoValue: {
    fontSize: 16,
    color: '#333',
    fontWeight: '600',
  },
  descriptionSection: {
    backgroundColor: 'white',
    padding: 20,
    marginTop: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  descriptionText: {
    fontSize: 16,
    color: '#666',
    lineHeight: 24,
  },
  contactSection: {
    backgroundColor: 'white',
    padding: 20,
    marginTop: 12,
  },
  contactItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  contactLabel: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  contactValue: {
    fontSize: 16,
    color: '#666',
  },
  actionSection: {
    padding: 20,
    marginTop: 12,
  },
  callButton: {
    backgroundColor: '#FF6B35',
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: 'center',
    marginBottom: 12,
  },
  callButtonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  shareButton: {
    backgroundColor: '#007AFF',
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: 'center',
  },
  shareButtonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  bottomSpacing: {
    height: 40,
  },
});

export default CarDetailScreen; 